package git.soulbgm.security.service.impl;

import git.soulbgm.pojo.vo.OnlineUserInfo;
import git.soulbgm.security.pojo.LoginUser;
import git.soulbgm.security.service.OnlineUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.session.SessionInformation;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 使用Session的在线用户服务
 *
 * @author SoulBGM
 * @date 2021-09-08
 */
@Service("sessionOnlineUserService")
public class SessionOnlineUserServiceImpl extends OnlineUserService {

    /**
     * 会话注册类
     */
    @Autowired
    private SessionRegistry sessionRegistry;

    @Override
    public List<OnlineUserInfo> getOnlineUser(String username, String loginIpAddress) {
        List<Object> allPrincipals = sessionRegistry.getAllPrincipals();
        List<OnlineUserInfo> onlineUserInfoList = new ArrayList<>(allPrincipals.size());
        for (Object p : allPrincipals) {
            // 查看在线用户的sessionId
            List<SessionInformation> allSessions = sessionRegistry.getAllSessions(p, false);
            for (SessionInformation s : allSessions) {
                LoginUser loginUser = (LoginUser) s.getPrincipal();
                addOnlineUserInfo(username, loginIpAddress, onlineUserInfoList, s.getSessionId(), loginUser);
            }
        }
        return onlineUserInfoList;
    }

    @Override
    public boolean forcedOfflineUser(List<String> sessionList) {
        try {
            for (String s : sessionList) {
                String[] split = s.split(":");
                String sessionId = split[0];
                sessionRegistry.removeSessionInformation(sessionId);
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
